package uutalk.netcloud.talk.base.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.baidu.mapapi.map.Marker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.util.DensityUtil;
import uutalk.netcloud.talk.model.bean.RadarInfo;

/**
 * @ClassName：RadarView
 * @Description：<雷达扫描视图>
 * @author：zihao
 * @date：2015年11月11日 上午12:26:11
 * @version：v1.1
 */
@SuppressLint("DrawAllocation")
public class RadarView extends View {

	private final static String TAG = "RadarView";
	private Context mContext;
	private boolean isSearching = false;// 标识是否处于扫描状态,默认为不在扫描状态
	private boolean isUpdateIcon = false;// 标识是否处于扫描状态,默认为不在扫描状态
	private Paint mPaint;// 画笔
	private Bitmap mScanBmp;// 执行扫描运动的图片
	private int mOffsetArgs = 0;// 扫描运动偏移量参数
	private Bitmap mDefaultPointBmp;// 标识设备的圆点-默认
	private Bitmap mLightPointBmp;// 标识设备的圆点-高亮

	private int mPointCount = 0;// 圆点总数
	private int mOldPointCount = 0;// 圆点总数
	private List<String> mPointArray = new ArrayList<String>();// 存放偏移量的map
	private Map<String, RadarInfo> radarPointBeanMap = new HashMap<>();// 存放偏移量的map
	private int mWidth, mHeight, mMaxRadius;
	private float mUserIconRadius, mOtherIconRadius;// 中心点的icon半径
	int mOutWidth;// 外圆宽度(w/4/5*2=w/10)
	int mCx, mCy;// x、y轴中心点
	int mOutsideRadius, mInsideRadius;// 外、内圆半径
	//数据区画笔
	private Paint valuePaint;
	private Paint textPaint;

	public RadarView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}

	public RadarView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public RadarView(Context context) {
		super(context);
		init(context);
	}

	/**
	 * 
	 * @return void
	 */
	private void init(Context context) {
		mPaint = new Paint();
		this.mContext = context;

		this.mDefaultPointBmp = Bitmap.createBitmap(BitmapFactory
				.decodeResource(mContext.getResources(),
						R.drawable.default_head));
		this.mLightPointBmp = Bitmap.createBitmap(BitmapFactory.decodeResource(
				mContext.getResources(), R.drawable.default_head));

		valuePaint=new Paint();
		valuePaint.setColor(Color.RED);
		valuePaint.setAntiAlias(true);
		valuePaint.setStyle(Style.FILL_AND_STROKE);


		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
		textPaint.setAntiAlias(true);
		textPaint.setTextSize(DensityUtil.dip2px(mContext, 8));
		textPaint.setStyle(Style.FILL_AND_STROKE);
	}

	/**
	 * 测量视图及其内容,以确定所测量的宽度和高度(测量获取控件尺寸).
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 获取控件区域宽高
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {

		if (mWidth == 0 || mHeight == 0) {
			final int minimumWidth = getSuggestedMinimumWidth();
			final int minimumHeight = getSuggestedMinimumHeight();
			mWidth = w;
			mHeight = h;


			// 获取x/y轴中心点
			mCx = mWidth / 2;
			mCy = mHeight / 2;

			// 获取外圆宽度
			mOutWidth = mWidth / 10;

			mScanBmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(
				mContext.getResources(), R.drawable.radar_scan_img), mWidth
				- mOutWidth, mWidth - mOutWidth, false);

			// 计算内、外半径
//			mOutsideRadius = mWidth / 2;// 外圆的半径
//			mInsideRadius = (mWidth - mOutWidth) / 4 / 2;// 内圆的半径,除最外层,其它圆的半径=层数*insideRadius
			mOutsideRadius = mWidth / 2 - mOutWidth;// 外圆的半径
			mInsideRadius = (mWidth -4* mOutWidth)/8;// 内圆的半径,除最外层,其它圆的半径=层数*insideRadius
			mUserIconRadius = mWidth * 1 / 18f;
			mOtherIconRadius = mUserIconRadius/2;
			mMaxRadius = mInsideRadius * 4;
		}

		super.onSizeChanged(w, h, oldw, oldh);
	}

	/**
	 * 绘制视图--从外部向内部绘制
	 */
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 开始绘制最外层的圆
		mPaint.setAntiAlias(true);// 设置抗锯齿
		mPaint.setStyle(Style.FILL);// 设置填充样式
		mPaint.setColor(0xffB8DCFC);// 设置画笔颜色
		// 1.开始绘制圆形
		canvas.drawCircle(mCx, mCy, mOutsideRadius, mPaint);

		// 开始绘制内4圆
		mPaint.setColor(0xff3278B4);
		canvas.drawCircle(mCx, mCy, mInsideRadius * 4, mPaint);

		// 开始绘制内3圆
		mPaint.setStyle(Style.STROKE);
		mPaint.setColor(0xff31C9F2);
		canvas.drawCircle(mCx, mCy, mInsideRadius * 3, mPaint);

		// 开始绘制内2圆
		canvas.drawCircle(mCx, mCy, mInsideRadius * 2, mPaint);

		// 开始绘制内1圆
		canvas.drawCircle(mCx, mCy, mInsideRadius * 1, mPaint);

		// 2.开始绘制对角线
		canvas.drawLine(mOutWidth / 2, mCy, mWidth - mOutWidth / 2, mCy, mPaint);// 绘制0°~180°对角线
		canvas.drawLine(mCx, mHeight - mOutWidth / 2, mCx, mOutWidth / 2,
				mPaint);// 绘制90°~270°对角线

		// 根据角度绘制对角线
		int startX, startY, endX, endY;
		double radian;

		// 绘制45°~225°对角线
		// 计算开始位置x/y坐标点
		radian = Math.toRadians((double) 45);// 将角度转换为弧度
		startX = (int) (mCx + mInsideRadius * 4 * Math.cos(radian));// 通过圆心坐标、半径和当前角度计算当前圆周的某点横坐标
		startY = (int) (mCy + mInsideRadius * 4 * Math.sin(radian));// 通过圆心坐标、半径和当前角度计算当前圆周的某点纵坐标
		// 计算结束位置x/y坐标点
		radian = Math.toRadians((double) 45 + 180);
		endX = (int) (mCx + mInsideRadius * 4 * Math.cos(radian));
		endY = (int) (mCy + mInsideRadius * 4 * Math.sin(radian));
		canvas.drawLine(startX, startY, endX, endY, mPaint);

		// 绘制135°~315°对角线
		// 计算开始位置x/y坐标点
		radian = Math.toRadians((double) 135);
		startX = (int) (mCx + mInsideRadius * 4 * Math.cos(radian));
		startY = (int) (mCy + mInsideRadius * 4 * Math.sin(radian));
		// 计算结束位置x/y坐标点
		radian = Math.toRadians((double) 135 + 180);
		endX = (int) (mCx + mInsideRadius * 4 * Math.cos(radian));
		endY = (int) (mCy + mInsideRadius * 4 * Math.sin(radian));
		canvas.drawLine(startX, startY, endX, endY, mPaint);

		// 3.绘制扫描扇形图
		canvas.save();// 用来保存Canvas的状态.save之后，可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作.
		//绘制小圆点
		valuePaint.setAlpha(255);

		if (isSearching) {// 判断是否处于扫描
			canvas.rotate(mOffsetArgs, mCx, mCy);// 绘制旋转角度,参数一：角度;参数二：x中心;参数三：y中心.
			canvas.drawBitmap(mScanBmp, mCx - mScanBmp.getWidth() / 2, mCy
					- mScanBmp.getHeight() / 2, null);// 绘制Bitmap扫描图片效果
			mOffsetArgs += 2;
		}
		else {
			canvas.drawBitmap(mScanBmp, mCx - mScanBmp.getWidth() / 2, mCy
					- mScanBmp.getHeight() / 2, valuePaint);
		}



//		if(isUpdateIcon){
//			drawCenterIcon(canvas);
//			isUpdateIcon = false;
//		}
		// 4.开始绘制动态点
		canvas.restore();// 用来恢复Canvas之前保存的状态.防止save后对Canvas执行的操作对后续的绘制有影响.

        drawCenterIcon(canvas);

		if (mPointCount > 0) {// 当圆点总数>0时,进入下一层判断

			if (mPointCount > mPointArray.size()) {// 当圆点总数大于存储坐标点数目时,说明有增加,需要重新生成随机坐标点
//				int mx = mInsideRadius + mRandom.nextInt(mInsideRadius * 6);
//				int my = mInsideRadius + mRandom.nextInt(mInsideRadius * 6);
//				mPointArray.add(mx + "/" + my);
			}



			drawCirclPoint(canvas);
			// 开始绘制坐标点
//			for (int i = 0; i < mPointArray.size(); i++) {
//				String[] result = mPointArray.get(i).split("/");
//
//
//				canvas.drawCircle(mCx+Integer.parseInt(result[0]),mCy+Integer.parseInt(result[1]),20,valuePaint);
				//canvas.drawBitmap(mDefaultPointBmp, mCx+Integer.parseInt(result[0]), mCy+Integer.parseInt(result[1]), null);
				//Log.e("test", "mCx+Integer.parseInt(result[0])>>"+(mCx+Integer.parseInt(result[0])));
				//Log.e("test", "mCy+Integer.parseInt(result[1]>>"+(mCy+Integer.parseInt(result[1])));

                //canvas.drawBitmap(mLightPointBmp, null, new Rect(mCx-fl, mCy-fl, mCx+fl, mCy+fl), valuePaint);
				// 开始绘制动态点
//				if (i < mPointArray.size() - 1)
//					canvas.drawBitmap(mDefaultPointBmp,
//							mCx+Integer.parseInt(result[0]),
//							mCy, null);
//				else
//					canvas.drawBitmap(mLightPointBmp,
//							mCx+Integer.parseInt(result[0]),
//							mCy, null);
//			}
			mOldPointCount ++;
		}

		if (isSearching)
			this.invalidate();
	}

	private void drawCirclPoint(Canvas canvas, float x, float y, String name){

		//Log.e(TAG, "mMaxRadius>>"+mMaxRadius+" x>>"+x+" y>>"+y);
		if(x<0){
			x-=mUserIconRadius;
			if(x<-mMaxRadius){
				x=-mMaxRadius;
			}
		} else {
			x+=mUserIconRadius;
			if(x>mMaxRadius){
				x=mMaxRadius;
			}
		}

		if(y<0){
			y-=mUserIconRadius;
			if(y<-mMaxRadius){
				y=-mMaxRadius;
			}
		} else {
			y+=mUserIconRadius;
			if(y>mMaxRadius){
				y=mMaxRadius;
			}
		}

		canvas.drawBitmap(mDefaultPointBmp, null,
				new Rect((int) (mCx+x-mOtherIconRadius), (int) (mCy+y -mOtherIconRadius),
						(int) (mCx+x + mOtherIconRadius), (int) (mCy+y + mOtherIconRadius)), valuePaint);
		canvas.drawText(name,mCx+x-mOtherIconRadius/2,mCy+y+ mOtherIconRadius/4,textPaint);
		//canvas.drawCircle(mCx+x, mCy+y,20, valuePaint);
	}

	private synchronized void drawCirclPoint(Canvas canvas){
		if(radarPointBeanMap!=null && radarPointBeanMap.size()>0){
			Iterator iterator = radarPointBeanMap.entrySet().iterator();
			Marker marker = null;
			while (iterator.hasNext()){
				Map.Entry<String, RadarInfo> entry = (Map.Entry<String, RadarInfo>)iterator.next();
				RadarInfo point = entry.getValue();
				drawCirclPoint(canvas, (float)(point.getX()), (float)point.getY(), point.getName());
			}
		}
	}

    /**
     * 绘制最中间的图标
     *
     * @param canvas
     */
    private void drawCenterIcon(Canvas canvas) {
        canvas.drawBitmap(mLightPointBmp, null,
                new Rect((int) (mWidth / 2 - mUserIconRadius), (int) (mHeight / 2 -mUserIconRadius),
                        (int) (mWidth / 2 + mUserIconRadius), (int) (mHeight / 2 + mUserIconRadius)), valuePaint);
    }

	/**
	 * @return void
	 */
	public void setSearching(boolean status) {
		this.isSearching = status;
		this.invalidate();
	}

	/**
	 * @return void
	 */
	public void addPoint() {
		mPointCount++;
		this.invalidate();
	}

	/**
	 * @return void
	 */
//	public void addPoint(Point point) {
//		mPointCount++;
//		mPointArray.add(point.x + "/" + point.y);
//		this.invalidate();
//	}

//	public void addPoint(String blueAddress, Point point){
//		mPointCount++;
//		radarPointBeanMap.put(blueAddress, point);
//		this.invalidate();
//	}

	public void addPoint(String blueAddress, RadarInfo radarInfo){
		mPointCount++;
		radarPointBeanMap.put(blueAddress, radarInfo);
		this.invalidate();
	}

	public void delete(){

	}
	 public void clearPoints(){
		 if(mPointArray!=null && mPointArray.size()>0){
			 mPointArray.clear();
		 }
		 mPointCount = 0;
	 }

	 public void setUserIcon(Bitmap bitmap){
		if(bitmap != null){
			this.mLightPointBmp = makeRoundCorner(bitmap);
			isUpdateIcon = true;
			this.invalidate();
		}
	 }

	/**
	 * 解析获取控件宽高
	 * 
	 * @return int
	 */
	private int resolveMeasured(int measureSpec, int desired) {
		int result = 0;
		int specSize = MeasureSpec.getSize(measureSpec);
		switch (MeasureSpec.getMode(measureSpec)) {
		case MeasureSpec.UNSPECIFIED:
			result = desired;
			break;
		case MeasureSpec.AT_MOST:
			result = Math.min(specSize, desired);
			break;
		case MeasureSpec.EXACTLY:
		default:
			result = specSize;
		}
		return result;
	}

	public static Bitmap makeRoundCorner(Bitmap bitmap, int px)
	{
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		int color = 0xff424242;
		Paint paint = new Paint();
		Rect rect = new Rect(0, 0, width, height);
		RectF rectF = new RectF(rect);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, px, px, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	public static Bitmap makeRoundCorner(Bitmap bitmap)
	{
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int left = 0, top = 0, right = width, bottom = height;
		float roundPx = height/2;
		if (width > height) {
			left = (width - height)/2;
			top = 0;
			right = left + height;
			bottom = height;
		} else if (height > width) {
			left = 0;
			top = (height - width)/2;
			right = width;
			bottom = top + width;
			roundPx = width/2;
		}
		Log.i("RadarView", "ps:"+ left +", "+ top +", "+ right +", "+ bottom);

		Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		int color = 0xff424242;
		Paint paint = new Paint();
		Rect rect = new Rect(left, top, right, bottom);
		RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}


}